import React, { useState } from 'react'
import Header from '@/components/Header'
import MySwiper from '@/components/MySwiper'
import MyNav from '@/components/MyNav'
import { secKillListApi, getProListApi, swiperApi } from '@/api/home'
import { useEffect } from 'react'
import SecKill from '@/components/SecKill'
import ProList from '@/components/ProList'
import { InfiniteScroll, DotLoading, PullToRefresh } from 'antd-mobile'
import { sleep } from 'antd-mobile/es/utils/sleep'

export default function Home() {
  // ? 在脚手架项目中(无论是VUE/React)使用,只要在数据中定义图片 使用的是静态相对路径地址 , 则会导致图片出现404的情况(因为执行npm run dev/npm run start, 会进行一个打包, 该打包后的包存在浏览器内存中 开发者看不到, 打包后的代码和执行npm run build效果基本一致,)
  // 如果使用静态路径数据图片导致打包后的图片的路径就变了(因为打包路径结构改变) 所以出现404

  // const [swiperArr,setSwiperArr] = useState([
  //   require('../assets/images/老张.jpg'),
  //   require('../assets/images/bcImg.webp'),
  //   require('../assets/images/laozhang1.webp')
  // ])
  const [swiperList, setSwiperList] = useState([])
  const [secKillArr, setSecKillArr] = useState([])
  const [proList, setProList] = useState([])
  const [count, setCount] = useState(1)
  const [hasMore, setHasMore] = useState(true) //是否更多
  async function loadMore() {
    // 每次滚动触发 loadMore 方法, 然后让当前页+1 则请求下一页数据
    setCount(count + 1)
    // append === res
    const append = await getProListApi({
      count
    })
    console.log('append', append);
    setProList(val => [...proList, ...append.data.data])
    setHasMore(append.data.data.length > 0)
  }
  const InfiniteScrollContent = ({ hasMore }) => {
    return (
      <>
        {hasMore ? (
          <>
            <span>Loading</span>
            <DotLoading />
          </>
        ) : (
          <span>--- 我是有底线的 ---</span>
        )}
      </>
    )
  }
  useEffect(() => {

    swiperApi().then(res => {
      console.log(res);

      setSwiperList(res.data.data)
    })

    // 请求秒杀数据
    secKillListApi({ count: 1, limitNum: 6 }).then(res => {
      console.log(res);
      setSecKillArr(res.data.data)
    })

    // 请求产品列表数据
    //   getProListApi({
    //     count: 1,
    //     limitNum: 10
    //   }).then(res => {
    //     console.log(res);
    //     setProList(res.data.data)
    //   })
  }, [])
  return (
    <div>
      {/* 头部组件 */}
      <Header></Header>
      {/* 轮播图组件 */}
      <PullToRefresh onRefresh={async () => {
        await sleep(1000)
        // 重新请求数据
        getProListApi({ count: 1 }).then(res => {
          setProList([...res.data.data])
          setCount(2)
        })
      }}>
        <MySwiper swiperList={swiperList}></MySwiper>
        {/* 导航组件 */}
        <MyNav></MyNav>
        {/* 秒杀组件 --- 父传子 */}
        <SecKill secKillArr={secKillArr}></SecKill>
        {/* 产品列表组件 */}

        <ProList proList={proList}></ProList>
        {/* 无限滚动组件 */}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} >
          <InfiniteScrollContent hasMore={hasMore} />
        </InfiniteScroll>
      </PullToRefresh>


    </div>
  )
}
